package com.wisco.web.demo.action;

import java.util.List;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;

import com.wisco.plarform.action.AbstractAction;
import com.wisco.plarform.core.ProjectException;
import com.wisco.web.demo.model.User;
import com.wisco.web.demo.service.UserService;

@Controller
public class UserAction extends AbstractAction {
	private static final long serialVersionUID = 2137376461864960882L;

	private User user = new User();
	
	@Resource
	private UserService userService;
	
	//列出所有的用户
	@Action(value = "/user_list", results = { @Result(name = SUCCESS, location = "/WEB-INF/jsp/demo/user_list.jsp") })
	public String list() throws Exception {

		List userList = userService.searchAllUser();
		
		this.getRequest().setAttribute("userList", userList);
		
		//this.getParameters().put("userList", userList);
		
		
		logger.debug("----------list()------------");
		
		return SUCCESS;
	}
	
	//创建用户
	@Action(value = "/user_create", results = { @Result(name = SUCCESS, location = "/WEB-INF/jsp/demo/user_list.jsp") })
	public String create() throws Exception {
		
		/*User user = new User();
		user.setPassword("123456");
		user.setUsername("admin_"+new Date().getTime());
		userService.createUser(user);*/
		
		User user = new User();
		user.setUserid(1005);
		user.setUsername("test41");
		user.setPassword("test11");
		
		User user1 = new User();
		user1.setUserid(1006);
		user1.setUsername("test61");
		user1.setPassword("test20");
		
		User user2 = new User();
		user2.setUserid(1007);
		user2.setUsername("test51");
		user2.setPassword("test31");
		
		User[] users = {user,user1,user2};
		try {
			
			userService.insertUsers(users);
		} catch (DataAccessException e) {
			throw new ProjectException(e.getMessage());
		}
		this.list();
		
		return SUCCESS;
	}

	//删除用户
	@Action(value = "/user_delete", results = { @Result(name = SUCCESS, location = "/WEB-INF/jsp/demo/user_list.jsp") })
	public String delete() throws Exception {

		return SUCCESS;
	}

	//更新用户
	@Action(value = "/user_update", results = { @Result(name = SUCCESS, location = "/WEB-INF/jsp/demo/user_list.jsp") })
	public String update() throws Exception {

		return SUCCESS;
	}
	
	@Override
	public User getViewModel() {
		return user;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
